package com.graduate.work.graduatework.Controller;

import com.graduate.work.graduatework.common.Result;
import com.graduate.work.graduatework.common.ResultStatus;
import com.graduate.work.graduatework.entity.Comment;
import com.graduate.work.graduatework.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Optional;

/**
 * @author: cuibingqi.
 * @date: 17/5/4 下午9:30.
 * @descripe:
 */
@Controller
@RequestMapping("comment")
public class CommentController {

    @Autowired
    private CommentService commentService;
    //添加评论
    @RequestMapping(value = "addcomment",method = RequestMethod.POST)
    public Result<Boolean> addComment(Comment comment){//刷新页面
        Result<Boolean> result = new Result<>(ResultStatus.SUCCESS.getCode(),ResultStatus.SUCCESS.getMsg());

        Optional<Comment> isComment = Optional.ofNullable(comment);
        if(!isComment.isPresent()) {
            result.setCode(ResultStatus.FAIL.getCode());
            result.setMsg(ResultStatus.FAIL.getMsg());
            return result;
        }
        result.setBody(commentService.addComment(comment));

        return result;
    }
    //删除评论
    @RequestMapping(value = "deletecomment/{id}",method = RequestMethod.POST)
    public Result<Boolean> deleteComment(@PathVariable int id){

        Result<Boolean> result = new Result<>(ResultStatus.SUCCESS.getCode(),ResultStatus.SUCCESS.getMsg());

        Optional<Integer> isId = Optional.ofNullable(id);
        if(!isId.isPresent()) {
            result.setCode(ResultStatus.FAIL.getCode());
            result.setMsg(ResultStatus.FAIL.getMsg());
            return result;
        }
        result.setBody(commentService.deleteComment(id));

        return result;
    }
    //查询评论
    @RequestMapping(value = "selectcomment/{flightNumber}",method = RequestMethod.POST)
    public String selectComment(@PathVariable String flightNumber,ModelMap modelMap){

        Result<List<Comment>> result = new Result<>(ResultStatus.SUCCESS.getCode(),ResultStatus.SUCCESS.getMsg());

        Optional<String> isFlightNumber = Optional.ofNullable(flightNumber);
        if(!isFlightNumber.isPresent()) {
            result.setCode(ResultStatus.FAIL.getCode());
            result.setMsg(ResultStatus.FAIL.getMsg());
            return "error";
        }
        result.setBody(commentService.selectComment(flightNumber));

        modelMap.addAttribute("selectCommentResult",result);

        return "selectComment";
    }
}
